#-*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import keras
from keras.utils import to_categorical
from keras.models import load_model
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from keras.datasets import mnist
from keras import models
from keras import layers

from keras.utils.vis_utils import plot_model


print"keras的版本是：",keras.__version__

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()#读取数据



print train_images.shape
print len(train_labels)
print train_labels
# Let's have a look at the test data:

print test_images.shape
print len(test_labels)
print test_labels



network = models.Sequential()#序列模型的意思就是想要设计的圣经网络是一层层堆起来的。
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))#28 * 28是像素
# 因为输入图片的像素是28*28,所以神经网络的第一层是784个节点
network.add(layers.Dense(10, activation='softmax'))



network.compile(optimizer='rmsprop',
                loss='categorical_crossentropy',
                metrics=['accuracy'])



train_images = train_images.reshape((60000, 28 * 28))#6万测试集
train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))#1万测试集
test_images = test_images.astype('float32') / 255


# We also need to categorically encode the labels, a step which we explain in chapter 3:
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)



if os.path.exists('model.h5')==True:#如果当前路径存在模型文件，那么就直接读取模型
    # 保存网络结构，载入网络结构
    network = load_model('model.h5') 

else:#否则，就重新开始训练模型，并且保存模型文件
    network.fit(train_images, train_labels, epochs=5, batch_size=128)#这里是在训练模型,一次epoch使用全部的训练数据集,batch_size指的是一批数据的大小。
    network.save('model.h5')

# Two quantities are being displayed during training: the "loss" of the network over the training data, and the accuracy of the network over 
# the training data.
# 
# We quickly reach an accuracy of 0.989 (i.e. 98.9%) on the training data. Now let's check that our model performs well on the test set too:



test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)


from keras.utils.vis_utils import model_to_dot
#model即为要可视化的网络模型

plot_model(network, to_file='network.png',show_shapes=True)#绘制神经网络结构



